//
//  KKEmoticonKeyboardView.swift
//  EmotionKeyBoard
//
//  Created by King.Kong. on 16/5/30.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit

private let emoticonCellId = "emoticonCellId"
private let toolBarHeight: CGFloat = 37
private let keyboardViewHeight: CGFloat = 220
class KKEmoticonKeyboardView: UIView {
    
    lazy var packages: [KKEmoticonPackage] = KKEmoticonManager.sharedEmoticonTools.packages


    override init(frame: CGRect) {
        //在视图内部制定frame
        let rect = CGRect(x: 0, y: 0, width: 0, height: keyboardViewHeight)
        super.init(frame: rect)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI界面
    private func setupUI() {
        //设置背景颜色
//        backgroundColor = UIColor.yellowColor()
        addSubview(toolbar)
        addSubview(collectionView)
        addSubview(pageControl)
        
        //设置约束
        toolbar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
            //设置高度
            //            make.height.equalTo(37)
            make.height.equalTo(toolBarHeight)
            
        }
        collectionView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(toolbar.snp_top)
        }
        pageControl.snp_makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.bottom.equalTo(toolbar.snp_top).offset(-5)
        }
        
        //实现闭包
        toolbar.selectedIndexCallBack = { (index: Int) -> () in
            print(index)
            //滚动collectionView
            let indexPath = NSIndexPath(forItem: 0, inSection: index)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            
            self.updatePageControl(indexPath)
        }
        
        dispatch_async(dispatch_get_main_queue()) {
            //设置初始的pageControl的信息
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
            self.updatePageControl(indexPath)
        }

    }
    
    private lazy var toolbar: KKEmoticonToolBar = KKEmoticonToolBar()
    
    //显示表情视图
    private lazy var collectionView: UICollectionView = {
        //流水布局
        let layout = UICollectionViewFlowLayout()
        //设置布局方向
        layout.scrollDirection = .Horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: keyboardViewHeight - toolBarHeight)
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.dataSource = self
        // 设置dialing
        cv.delegate = self
        //注册cell
        cv.registerClass(EmoticonPageCell.self, forCellWithReuseIdentifier: emoticonCellId)
        //设置分页滚动
        cv.pagingEnabled = true
        //
        cv.bounces = false
        cv.backgroundColor = UIColor(white: 0.95, alpha: 1)
        return cv
    }()
    
    //添加pageControl控件
    private lazy var pageControl: UIPageControl = {
        let p = UIPageControl()
        
        //设置总页数
        p.numberOfPages = 6
        //设置当前选中页面
        p.currentPage = 4
        //设置不可交互
        p.userInteractionEnabled = false
        //        p.currentPageIndicatorTintColor = UIColor.redColor()
        //        p.pageIndicatorTintColor = UIColor.blueColor()
        p.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        p.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        return p
    }()

}


//数据源方法
extension KKEmoticonKeyboardView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    //多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    
    //每组有两个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //根据section 获取分组表情的二维数组的数量
        return packages[section].sectionEmoticon.count

    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellId, forIndexPath: indexPath) as! EmoticonPageCell
        
//        cell.backgroundColor = randomColor()
        cell.emoticons = packages[indexPath.section].sectionEmoticon[indexPath.item]
        return cell
    }
    
    //减速结束的时候 获取到显示的cell
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
//        let indexPaths = collectionView.indexPathsForVisibleItems()
//        //减速结束的时候
//        let indexPath = indexPaths.last
//        //可以设置toolbar选中的按钮
//        toolbar.setSelectedBtn(indexPath!.section)
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //TODO:获取collectionView的 '中心点' 所在的的位置
        var center =  collectionView.center
        center.x = center.x + collectionView.contentOffset.x
        //判断当前屏幕显示的两个cell的frame 谁包含了这个中心点
        let indexPaths = collectionView.indexPathsForVisibleItems()

        for indexPath in indexPaths {
            let cell = collectionView.cellForItemAtIndexPath(indexPath)
            //判断frame是否包含了 '中心点'
            if cell!.frame.contains(center) {
                //跟新pageControld的数据
                updatePageControl(indexPath)
                //可以设置toolbar选中的按钮
                toolbar.setSelectedBtn(indexPath.section)
            }
        }
    }
        private func updatePageControl(indexPath: NSIndexPath) {
            //可以根据indexPath.section 获取
            pageControl.numberOfPages = packages[indexPath.section].sectionEmoticon.count
            
            pageControl.currentPage = indexPath.item
        
}
}
